package com.zengde.zxfy.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zengde.zxfy.common.PageBean;
import com.zengde.zxfy.dto.EmpPageQueryDTO;
import com.zengde.zxfy.entity.Emp;
import com.zengde.zxfy.entity.EmpExpr;
import com.zengde.zxfy.mapper.EmpExprMapper;
import com.zengde.zxfy.mapper.EmpMapper;
import com.zengde.zxfy.service.EmpService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class EmpServiceImpl implements EmpService {
    private static final Logger log = LoggerFactory.getLogger(EmpServiceImpl.class);
    private final EmpMapper empMapper;
    private final EmpExprMapper empExprMapper;

    public EmpServiceImpl(EmpMapper empMapper, EmpExprMapper empExprMapper) {
        this.empMapper = empMapper;
        this.empExprMapper = empExprMapper;
    }

    @Override
    public PageBean<Emp> list(EmpPageQueryDTO empPageQueryDTO) {
        log.debug("开始分页查询，参数：{}", empPageQueryDTO);
        PageHelper.startPage(empPageQueryDTO.getPage(), empPageQueryDTO.getPageSize());
        Page<Emp> page = (Page<Emp>) empMapper.list(empPageQueryDTO);
        log.debug("查询结果：总记录数 {}，当前页数据量 {}", page.getTotal(), page.size());
        return new PageBean<>(page.getTotal(), page.getResult());
    }

    @Override
    @Transactional
    public Integer add(Emp emp) {
        // 设置默认密码
        emp.setPassword("123456");
        empMapper.insert(emp);
        
        // 保存工作经历
        if (emp.getExperiences() != null && !emp.getExperiences().isEmpty()) {
            empExprMapper.insertBatch(emp.getId(), emp.getExperiences());
        }
        
        return emp.getId();
    }

    @Override
    @Transactional
    public void update(Emp emp) {
        empMapper.update(emp);
        
        // 更新工作经历
        if (emp.getExperiences() != null) {
            empExprMapper.deleteByEmpId(emp.getId());
            if (!emp.getExperiences().isEmpty()) {
                empExprMapper.insertBatch(emp.getId(), emp.getExperiences());
            }
        }
    }

    @Override
    @Transactional
    public void delete(Integer id) {
        empMapper.delete(id);
        empExprMapper.deleteByEmpId(id);
    }

    @Override
    @Transactional
    public void deleteBatch(List<Integer> ids) {
        empMapper.deleteBatch(ids);
        for (Integer id : ids) {
            empExprMapper.deleteByEmpId(id);
        }
    }

    @Override
    public Emp getById(Integer id) {
        Emp emp = empMapper.getById(id);
        if (emp != null) {
            emp.setExperiences(empExprMapper.getByEmpId(id));
        }
        return emp;
    }

    @Override
    public Emp getByUsername(String username) {
        return empMapper.getByUsername(username);
    }
} 